self.onmessage = async (e) => {
  const { file, quality, targetFormat } = e.data as { file: File; quality: number; targetFormat: string }

  const compressImage = async (file: File, quality: number, format: string) => {
    return new Promise(resolve => {

      createImageBitmap(file).then(resp => {
        const offscreenCanvas = new OffscreenCanvas(resp.width, resp.height)
        const ctx = offscreenCanvas.getContext('2d')!
        ctx.drawImage(resp, 0, 0, offscreenCanvas.width, offscreenCanvas.height)
        offscreenCanvas.convertToBlob({
          quality,
          type: `image/${format}`
        }).then(blob => {
          const compressFile = new File([blob!], file.name, {
            type: `image/${format}`,
            lastModified: Date.now()
          })
          resolve(compressFile)
        })
      })
    })
  }

  const processFile = await compressImage(file, quality, targetFormat)
  postMessage(processFile)
}